<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { UploadInstance, UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Delete, Search } from '@element-plus/icons-vue'
import { deleteSale, searchSalePage } from '@/composables/sale'
import { useRoute, RouterLink } from 'vue-router'
import { getPageParams, setPageParams, getPageData, setPageData } from '@/composables/page-data'
import { globalProperties } from '@/composables/global-properties'

const upload = ref<UploadInstance>() 
const saleList = ref([] as Sale[])
const loading = ref(false) 
const url = globalProperties().rootUrl
const params = reactive({
  pageNum: 1,
  saleCode: ''
})
const pagination = ref({
  total: 0,
  pageCount: 0
})
const route = useRoute();
interface Sale{
  id: number,
  code: string,
  batchNo: string,
  amount: number,
  financeStatus: string,
  submitTime: string,
  finishTime: string,
  state: string,
  createTime: string
};

getPageParams(route.name as string).then(response=>{
  if(response){ 
    params.saleCode = response.saleCode
    params.pageNum = response.pageNum
  }
})

getPageData(route.name as string).then(data =>{
  if(data){
    saleList.value = data.saleList
    pagination.value = data.pagination
  }
})


const handleAvatarSuccess: UploadProps['onSuccess'] = ( response ) => {
  upload.value!.clearFiles()
  loading.value = false
  if(response?.code == 0){
    saleList.value = response.value.content
    params.pageNum = 1
    params.saleCode = ''
    pagination.value.total = response.value.page.totalElements
    pagination.value.pageCount = response.value.page.totalPages
    setPageParams(route.name as string, params)   
    setPageData(route.name as string, {"saleList":saleList.value, "pagination":pagination.value})
  }else{
    ElMessage({message:response.message, type:'error', duration:5000, showClose : true})
  }
}

const handleAvatarError:  UploadProps['onError'] = (response) => {
  loading.value = false
  ElMessage({message:response.message, type:'error', duration:5000, showClose : true})
}

const handleBeforeUpload: UploadProps['beforeUpload'] = rawFile => {
  loading.value = true
}


function deleteRow(sale: Sale) {
  if(sale?.id){
    loading.value = true
    deleteSale(sale.id)
    .then((response:string)=>{
      search()
      ElMessage({message: response, type:'success', duration:2500, showClose : true}) 
    })
    .catch((error:string)=> ElMessage({message: error, type:'error', duration:2500, showClose : true}))
    .finally(()=>loading.value = false)
  } 
} 

function search(){
  loading.value = true
  setPageParams(route.name as string, params)    
  searchSalePage(JSON.stringify(params))
  .then((response: any)=>{
    saleList.value = response.content
    pagination.value.total = response.page.totalElements
    pagination.value.pageCount = response.page.totalPages
    setPageData(route.name as string, {"saleList":saleList.value, "pagination":pagination.value})
  })
  .catch((error: string) => ElMessage({message: error, type:'error', duration:2500, showClose : true})) 
  .finally(()=>loading.value = false)
}

function saleParamsChanged(value:string){
  if(value?.length == 0){
    setPageParams(route.name as string, params)
  }
}

function handleCurrentChange(pageNum: number){
  params.pageNum = pageNum
  search()
}
</script>

<template>
    <div class="common-layout">
      <el-container>
        <el-header class="d-flex justify-content-between header">
          <el-form :inline="true" :model="params" size="small">
            <el-form-item label="订单号">
              <el-input v-model="params.saleCode" placeholder="订单号" clearable @input="saleParamsChanged" style="width: 160px" />
            </el-form-item>
            <el-form-item>
              <el-button :icon="Search" type="primary" @click="search" class="ms-1" :disabled="loading"/>
            </el-form-item>
          </el-form>
          <div class="d-flex">
            <el-upload
              ref="upload"
              :action="url + '/sale/upload'"
              :limit="1"
              :show-file-list=false
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload = "handleBeforeUpload"
              size="small"
            >
                <el-button type="primary">上传(.xls)</el-button>  
            </el-upload>
          </div>
        </el-header>
        <el-main class="py-0">        
          <el-table v-if="saleList" :data="saleList" stripe v-loading="loading" style="width: 100%">
            <el-table-column type="index" width="60" label="序号" />
            <el-table-column prop="code" label="主订单编号" width="180" />
            <el-table-column prop="amount" label="金额" width="100" />
            <el-table-column prop="submitTime" label="订单提交时间" width="160" />
            <el-table-column prop="finishTime" label="订单完成时间"  width="160" />
            <el-table-column prop="state" label="订单状态"  width="120" />
            <el-table-column prop="financeStatus" label="核销状态"  width="120" />
            <el-table-column prop="batchNo" label="导入批次号"  width="140" />
            <el-table-column prop="createTime" label="导入时间" width="160" />
            <el-table-column fixed="right" label="操作" min-width="120">
              <template #default="scope">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  content="删除"
                  placement="top"
                >
                  <el-button type="danger" :icon="Delete" circle size="small" @click="deleteRow(scope.row)" />
                </el-tooltip>         
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else v-loading="loading" description="暂无数据" />
          <el-pagination
            v-model:current-page="params.pageNum"
            :page-size="12"
            size="small"
            layout="total, prev, pager, next"
            :total="pagination.total"
            :page-count="pagination.pageCount"
            @current-change="handleCurrentChange"
          />
        </el-main>
      </el-container>
    </div>
</template>

<style lang="css" scoped>
.header{
    height: 2.2rem;
}
</style>